package com.hellobike.haxing.modules.wms.controller;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.wms.dto.ExportStockBatchLocDto;
import com.hellobike.haxing.modules.wms.dto.StockBatchLocDto;
import com.hellobike.haxing.modules.wms.entity.StockBatchLoc;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.facade.WmsStockFacade;
import com.hellobike.haxing.modules.wms.service.IStockBatchLocService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: t_wms_stock_batch_loc
 * @Author: haxing-boot
 * @Date: 2020-01-09
 * @Version: V1.0
 */
@RestController
@RequestMapping("/wms/stockBatchLoc")
@Slf4j
public class StockBatchLocController extends WmsBaseController<StockBatchLoc, IStockBatchLocService> {
    @Autowired
    private IStockBatchLocService stockBatchLocService;

    @Autowired
    private WmsStockFacade wmsStockFacade;

    /**
     * 分页列表查询
     *
     * @param stockBatchLoc
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "t_wms_stock_batch_loc-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StockBatchLocDto stockBatchLoc,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        stockBatchLoc.setWarehouseId(getWarehouseId());
        Page<StockBatchLocDto> page = new Page<>(pageNo, pageSize);
        IPage<StockBatchLocDto> pageList = stockBatchLocService.pageByStockBatchLocDto(page, stockBatchLoc);
        if (!CollectionUtils.isEmpty(pageList.getRecords())) {

            pageList.getRecords().forEach(stockBatchLocDto -> {
                if (!StringUtils.isEmpty(stockBatchLocDto.getSpecifications())) {
                    try {
                        JSONArray jsonArray = JSON.parseArray(stockBatchLocDto.getSpecifications());
                        if (jsonArray != null && jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                if ("保质期".equals(jsonObject.getString("name"))) {
                                    stockBatchLocDto.setExpiryDate(jsonObject.getString("value"));
                                }
                            }
                        }
                    } catch (Exception ex) {
                        log.error("", ex);
                    }

                }
            });

        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param stockBatchLoc
     * @return
     */
    @AutoLog(value = "t_wms_stock_batch_loc-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody StockBatchLoc stockBatchLoc) {
        stockBatchLocService.save(stockBatchLoc);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param param
     * @return
     */
    @AutoLog(value = "t_wms_stock_batch_loc-损溢", operateType = 3)
    @PutMapping(value = "/increaseAndDecrease")
    public Result<?> increaseAndDecrease(@RequestBody JSONObject param) {
//       stockBatchLocService.updateById(stockBatchLoc);
        Long id = param.getLong("id");
        Integer type = param.getInteger("syType");
        BigDecimal qty = param.getBigDecimal("qty");
        String note = param.getString("note");
        try {
            wmsStockFacade.increaseAndDecrease(id, type, qty, note, getWarehouseId(), getSysUserId());
        } catch (Exception e) {
            log.error("", e);
            return Result.error(e.getMessage());
        }
        return Result.ok("损溢操作成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "t_wms_stock_batch_loc-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        stockBatchLocService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "t_wms_stock_batch_loc-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.stockBatchLocService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StockBatchLoc stockBatchLoc = stockBatchLocService.getById(id);
        if (stockBatchLoc == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(stockBatchLoc);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param stockBatchLoc
     */
    @AutoLog(value = "t_wms_stock_batch_loc-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StockBatchLocDto stockBatchLoc) throws WmsExportException {
        try {
            Long warehouseId = getWarehouseId();
            stockBatchLoc.setWarehouseId(warehouseId);
            String title = "库区库存-" + warehouseId;
            List<ExportStockBatchLocDto> exportList = wmsExportFacade.exportStockBatchLoc(stockBatchLoc);
            return export(title, ExportStockBatchLocDto.class, exportList);
        } catch (Exception e) {
            throw new WmsExportException(e);
        }
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "t_wms_stock_batch_loc-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StockBatchLoc.class);
    }


}
